package xyz.eden.boot.common.web.tool;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @author gavin
 * @version 1.0
 * @descriptor
 * @date 2023/3/10 14:51
 */
public class WebTool {

    /**
     * 获取 HttpServletResponse
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = getServletRequestAttributes();
        return requestAttributes.getResponse();
    }

    /**
     * 获取 HttpServletRequest
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = getServletRequestAttributes();
        return requestAttributes.getRequest();
    }

    /**
     * 获取 ServletRequestAttributes
     *
     * @return
     */
    private static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 通过 Response 写信息
     *
     * @param response
     * @param msg
     */
    public static void writerInfoByRes(HttpServletResponse response, String msg) {
        PrintWriter writer = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            writer = response.getWriter();
            writer.println(msg);
            response.flushBuffer();
        } catch (Exception e) {

        } finally {
            if (Objects.nonNull(writer)) {
                writer.flush();
                writer.close();
            }
        }
    }

    /**
     * 获取请求 IP
     *
     * @return
     */
    public static String getReqIp() {
        HttpServletRequest request = getRequest();
        return getReqIp(request);
    }

    /**
     * 获取请求 IP
     *
     * @return
     */
    public static String getReqIp(HttpServletRequest request) {
        if (Objects.isNull(request)) {
            return "127.0.0.1";
        }
        return IpTool.getRemoteRealIp(request);
    }

}
